﻿using Furion.DatabaseAccessor;
using Furion.DatabaseAccessor.Extensions;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Furion.FriendlyException;
using Admin.NET.Core;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Linq.Dynamic.Core;
using Microsoft.AspNetCore.Http;
using System.Text;
using System.Web;
using Furion.RemoteRequest.Extensions;
using Furion;
using Serilog;

namespace Admin.NET.Application
{
    /// <summary>
    /// 收货单服务
    /// </summary>
    [ApiDescriptionSettings("收货单", Name = "WmsReceiptOrder", Order = 100)]
    [Route("api/[Controller]")]
    public class WmsReceiptOrderService : IWmsReceiptOrderService, IDynamicApiController, ITransient
    {
        private readonly IRepository<WmsReceiptOrder,MasterDbContextLocator> _wmsReceiptOrderRep;
        private readonly IRepository<SysDictType, MasterDbContextLocator> _sysDictTypeRep;
        private readonly IRepository<SysDictData, MasterDbContextLocator> _sysDictDataRep;
        private readonly ISysExcelTemplateService _sysExcelTemplateService;
        private readonly static object _lock = new();
        private readonly IRepository<WmsReceiptOrderDetails, MasterDbContextLocator> _wmsReceiptOrderDetailsRep;
        private readonly IRepository<WmsOrder, MasterDbContextLocator> _wmsOrderRep;
        private readonly IRepository<WmsOrderDetails, MasterDbContextLocator> _wmsOrderDetailsRep;
        private readonly IRepository<WmsOrderType, MasterDbContextLocator> _wmsOrderTypeRep;


        public WmsReceiptOrderService(
            IRepository<WmsReceiptOrder,MasterDbContextLocator> wmsReceiptOrderRep
            ,IRepository<SysDictType, MasterDbContextLocator> sysDictTypeRep
            ,IRepository<SysDictData, MasterDbContextLocator> sysDictDataRep
            ,ISysExcelTemplateService sysExcelTemplateService
            , IRepository<WmsReceiptOrderDetails, MasterDbContextLocator> wmsReceiptOrderDetailsRep
            , IRepository<WmsOrder, MasterDbContextLocator> wmsOrderRep
            , IRepository<WmsOrderDetails, MasterDbContextLocator> wmsOrderDetailsRep
            , IRepository<WmsOrderType, MasterDbContextLocator> wmsOrderTypeRep

        )
        {
            _wmsReceiptOrderRep = wmsReceiptOrderRep;
         _sysDictTypeRep = sysDictTypeRep;
         _sysDictDataRep = sysDictDataRep;
         _sysExcelTemplateService = sysExcelTemplateService;
            _wmsReceiptOrderDetailsRep = wmsReceiptOrderDetailsRep;
            _wmsOrderRep = wmsOrderRep;
            _wmsOrderDetailsRep = wmsOrderDetailsRep;
            _wmsOrderTypeRep = wmsOrderTypeRep;
        }

        /// <summary>
        /// 分页查询收货单
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet("page")]
        public async Task<PageResult<WmsReceiptOrderOutput>> Page([FromQuery] WmsReceiptOrderSearch input)
        {
            var wmsReceiptOrders = await _wmsReceiptOrderRep.DetachedEntities
                                     .Where(!string.IsNullOrEmpty(input.NO), u => EF.Functions.Like(u.NO, $"%{input.NO.Trim()}%"))
                                     .Where(!string.IsNullOrEmpty(input.SourceBillNo), u => EF.Functions.Like(u.SourceBillNo, $"%{input.SourceBillNo.Trim()}%"))
                                     .Where(!string.IsNullOrEmpty(input.Vendorcode), u => EF.Functions.Like(u.Vendorcode, $"%{input.Vendorcode.Trim()}%"))
                                     .Where(!string.IsNullOrEmpty(input.Vendorname), u => EF.Functions.Like(u.Vendorname, $"%{input.Vendorname.Trim()}%"))
                                     .Where(!string.IsNullOrEmpty(input.Companyname), u => EF.Functions.Like(u.Companyname, $"%{input.Companyname.Trim()}%"))
                                     .Where(!string.IsNullOrEmpty(input.WarehouseKeepername), u => EF.Functions.Like(u.WarehouseKeepername, $"%{input.WarehouseKeepername.Trim()}%"))
                                     .Where(input.TradeMode != null, u => u.TradeMode == input.TradeMode)
                                     .Where(!string.IsNullOrEmpty(input.WarehouseCentername), u => EF.Functions.Like(u.WarehouseCentername, $"%{input.WarehouseCentername.Trim()}%"))
                                     .Where(!string.IsNullOrEmpty(input.StoreRoomname), u => EF.Functions.Like(u.StoreRoomname, $"%{input.StoreRoomname.Trim()}%"))
                                     .Where(!string.IsNullOrEmpty(input.DeclarationCode), u => EF.Functions.Like(u.DeclarationCode, $"%{input.DeclarationCode.Trim()}%"))
                                     .Where(!string.IsNullOrEmpty(input.Majorname), u => EF.Functions.Like(u.Majorname, $"%{input.Majorname.Trim()}%"))
                                     //.Where(input.OrderStatus != null, u => u.OrderStatus == input.OrderStatus)
                                     .OrderBy(PageInputOrder.OrderBuilder<WmsReceiptOrderSearch>(input))
                                     .ProjectToType<WmsReceiptOrderOutput>()
                                     .ToADPagedListAsync(input.PageNo, input.PageSize);
            return wmsReceiptOrders;
        }
        /// <summary>
        /// 获取单据明细
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet("PageDetail")]
        public async Task<PageResult<WmsReceiptOrderDetailOutput>> PageDetail([FromQuery] ReceiptageDetailInput input)
        {
            var wmsOrders = await _wmsReceiptOrderDetailsRep.DetachedEntities
                                     .Where(input.Id != null, u => u.OrderId == input.Id)
                                     .ProjectToType<WmsReceiptOrderDetailOutput>()
                                     .ToADPagedListAsync(input.PageNo, input.PageSize);
            return wmsOrders;
        }

        /// <summary>
        /// pc确认收货
        /// </summary>
        /// <returns></returns>
        [HttpPost("PcConfirmReceipt")]
        [UnitOfWork]
        public async Task PcConfirmReceipt([FromBody] PcConfirmReceiptInput input)
        {
            if (input.GetOrderDetailOutputList.Count == 0) throw Oops.Oh("收货信息不能为空！");
            //获取主单据
            var wmsOrderModal = await _wmsReceiptOrderRep
                                     .FirstOrDefaultAsync(u => u.NO == input.NO);
            if (wmsOrderModal == null) throw Oops.Oh("单据不存在!");
            if (wmsOrderModal.ReceivingStatus == ReceivingStatus.YISHOUHUO) throw Oops.Oh("该单据已收货!");

            if (input.GetOrderDetailOutputList.Count == 0) throw Oops.Oh("收货信息不能为空！");
            //更新收货明细
            foreach (var item in input.GetOrderDetailOutputList)
            {
                var WmsReceiptOrderDetailsModal = item.Adapt<WmsReceiptOrderDetails>();
                if (WmsReceiptOrderDetailsModal.ReceivedQty < WmsReceiptOrderDetailsModal.DeliveryQty)
                {
                    WmsReceiptOrderDetailsModal.ReceivingStatus = ReceivingStatus.SHOUHUOZHONG;
                }
                else
                {
                    WmsReceiptOrderDetailsModal.ReceivingStatus = ReceivingStatus.YISHOUHUO;
                    
                }
                await _wmsReceiptOrderDetailsRep.UpdateNowAsync(WmsReceiptOrderDetailsModal);
            }
            //获取该收货单所有单据明细数量
            var allCount = await _wmsReceiptOrderDetailsRep.Where(x => x.OrderId == wmsOrderModal.Id).ToListAsync();
            //获取该收货单所有完成的单据明细
            var wcCount =await _wmsReceiptOrderDetailsRep.Where(x=>x.OrderId == wmsOrderModal.Id && x.ReceivingStatus == ReceivingStatus.YISHOUHUO).ToListAsync();
            if (allCount.Count == wcCount.Count)
            {
                wmsOrderModal.ReceivingStatus = ReceivingStatus.YISHOUHUO;
            }
            else if (allCount.Count > wcCount.Count && wcCount.Count>0)
            {
                wmsOrderModal.ReceivingStatus = ReceivingStatus.SHOUHUOZHONG;
            }
            else
            {
                wmsOrderModal.ReceivingStatus = ReceivingStatus.WEISHOUHUO;
            }
            await _wmsReceiptOrderRep.UpdateAsync(wmsOrderModal);
            //此步骤应该放在获取报检结果后为合格使用，现测试先在收货增加入库单
            //收货完成时添加进入库单
            //查询入库单是否有单据一致的，如果没有则添加入库单主单据
            var wmsOrdermodal = await _wmsOrderRep.FirstOrDefaultAsync(x => x.NO == input.NO);
            long Id = Yitter.IdGenerator.YitIdHelper.NextId();
            if (wmsOrdermodal == null)
            {
                var insertModal = wmsOrderModal.Adapt<WmsOrder>();
                // 查询单据小类是“生产入库”的Id
                var wmsOrderType = await _wmsOrderTypeRep.FirstOrDefaultAsync(z => z.Name.Contains("生产入库"));
                insertModal.Id = Id;
                insertModal.OrderLargeCategory = wmsOrderType != null ? wmsOrderType.Pid : 0;
                insertModal.OrderSubclass = wmsOrderType != null ? wmsOrderType.Id : 0;
                insertModal.OrderStatus = OrderStatusEnum.WEIXIAFA;
                await _wmsOrderRep.InsertAsync(insertModal);
            }
            else
            {
                Id = wmsOrdermodal.Id;
            }
            //添加明细
            foreach (var item in input.GetOrderDetailOutputList)
            {
                var wmsOrderDetailsModal = item.Adapt<WmsOrderDetails>();
                wmsOrderDetailsModal.OrderId = Id;
                wmsOrderDetailsModal.Qty = item.ReceivedQty;
                await _wmsOrderDetailsRep.InsertAsync(wmsOrderDetailsModal);
            }
        }

        /// <summary>
        /// 不分页查询收货单列表
        /// </summary>
        /// <param name="input">收货单查询参数</param>
        /// <returns>(收货单)实例列表</returns>
        [HttpGet("listNonPage")]
        public async Task<List<WmsReceiptOrderOutput>> ListNonPageAsync([FromQuery] WmsReceiptOrderSearchNonPage input)
        {
            var pNO = input.NO?.Trim() ?? "";
            var pSourceBillNo = input.SourceBillNo?.Trim() ?? "";
            var pVendorcode = input.Vendorcode?.Trim() ?? "";
            var pVendorname = input.Vendorname?.Trim() ?? "";
            var pCompanyname = input.Companyname?.Trim() ?? "";
            var pWarehouseKeepername = input.WarehouseKeepername?.Trim() ?? "";
            var pTradeMode = input.TradeMode;
            var pWarehouseCentername = input.WarehouseCentername?.Trim() ?? "";
            var pStoreRoomname = input.StoreRoomname?.Trim() ?? "";
            var pDeclarationCode = input.DeclarationCode?.Trim() ?? "";
            var pMajorname = input.Majorname?.Trim() ?? "";
            var pOrderStatus = input.OrderStatus;
            var wmsReceiptOrders = await _wmsReceiptOrderRep.DetachedEntities
                .Where(!string.IsNullOrEmpty(pNO), u => EF.Functions.Like(u.NO, $"%{pNO}%")) 
                .Where(!string.IsNullOrEmpty(pSourceBillNo), u => EF.Functions.Like(u.SourceBillNo, $"%{pSourceBillNo}%")) 
                .Where(!string.IsNullOrEmpty(pVendorcode), u => EF.Functions.Like(u.Vendorcode, $"%{pVendorcode}%")) 
                .Where(!string.IsNullOrEmpty(pVendorname), u => EF.Functions.Like(u.Vendorname, $"%{pVendorname}%")) 
                .Where(!string.IsNullOrEmpty(pCompanyname), u => EF.Functions.Like(u.Companyname, $"%{pCompanyname}%")) 
                .Where(!string.IsNullOrEmpty(pWarehouseKeepername), u => EF.Functions.Like(u.WarehouseKeepername, $"%{pWarehouseKeepername}%")) 
                .Where(pTradeMode != null, u => u.TradeMode == pTradeMode)
                .Where(!string.IsNullOrEmpty(pWarehouseCentername), u => EF.Functions.Like(u.WarehouseCentername, $"%{pWarehouseCentername}%")) 
                .Where(!string.IsNullOrEmpty(pStoreRoomname), u => EF.Functions.Like(u.StoreRoomname, $"%{pStoreRoomname}%")) 
                .Where(!string.IsNullOrEmpty(pDeclarationCode), u => EF.Functions.Like(u.DeclarationCode, $"%{pDeclarationCode}%")) 
                .Where(!string.IsNullOrEmpty(pMajorname), u => EF.Functions.Like(u.Majorname, $"%{pMajorname}%")) 
                //.Where(pOrderStatus != null, u => u.OrderStatus == pOrderStatus)
            .OrderBy(PageInputOrder.OrderNonPageBuilder(input))
            .ProjectToType<WmsReceiptOrderOutput>()
            .ToListAsync();
            return wmsReceiptOrders;
        }


        /// <summary>
        /// 增加收货单(yigo系统获取)
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("add")]
        [UnitOfWork]
        public async Task Add()
        {
            //获取入库通知单
            string url = App.Configuration["YiGoWebApi:QueryInboundNotice"];
            var Billdate_S = DateTime.Now.AddDays(-15).ToString("yyyy-MM-dd");
            var Billdate_E = DateTime.Now.AddDays(15).ToString("yyyy-MM-dd");
            //写日志文件
            //Log.Error($"[TransferContainerCode][ContainerCode:{input.ContainerCode}][url:{url}]");
            var response = await url.SetHttpMethod(System.Net.Http.HttpMethod.Post)
                                    .SetBody(new Dictionary<string, object> {
                                            { "Billdate_S", Billdate_S },
                                            { "Billdate_E", Billdate_E},
                                    }, "application/json").PostAsStringAsync();
            var Data = response.FromJson<WmsReceiptOrderOutputByYiGO>();
            var wmsOrderType = await _wmsOrderTypeRep.FirstOrDefaultAsync(z => z.Name.Contains("收货入库"));
            foreach (var item in Data.Data)
            {
                item.Id= Yitter.IdGenerator.YitIdHelper.NextId();
                var wmsReceiptOrder = item.Adapt<WmsReceiptOrder>();
                //判断是否存在相同的单据号
                var isExcit = await _wmsReceiptOrderRep.AnyAsync(x => x.NO == item.NO);
                if (!isExcit)
                {
                    wmsReceiptOrder.WMSNO = item.NO;//暂时使用yigo的单号，后续待定
                    wmsReceiptOrder.OrderLargeCategory = wmsOrderType != null ? wmsOrderType.Pid : 0;
                    wmsReceiptOrder.OrderSubclass = wmsOrderType != null ? wmsOrderType.Id : 0;
                    await _wmsReceiptOrderRep.InsertNowAsync(wmsReceiptOrder);
                    foreach (var item1 in item.Dtls)
                    {
                        var wmsReceiptOrderDeatail = item1.Adapt<WmsReceiptOrderDetails>();
                        wmsReceiptOrderDeatail.OrderId = item.Id;
                        await _wmsReceiptOrderDetailsRep.InsertNowAsync(wmsReceiptOrderDeatail);
                    }
                }
            }
        }

        /// <summary>
        /// 删除收货单
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("delete")]
        public async Task Delete(DeleteWmsReceiptOrderInput input)
        {
            var wmsReceiptOrder = await _wmsReceiptOrderRep.FirstOrDefaultAsync(u => u.Id == input.Id);
            await _wmsReceiptOrderRep.DeleteAsync(wmsReceiptOrder);
        }

        /// <summary>
        /// 更新收货单
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("edit")]
        public async Task Update(UpdateWmsReceiptOrderInput input)
        {
            var isExist = await _wmsReceiptOrderRep.AnyAsync(u => u.Id == input.Id, false);
            if (!isExist) throw Oops.Oh(ErrorCode.D3000);

            var wmsReceiptOrder = input.Adapt<WmsReceiptOrder>();
            await _wmsReceiptOrderRep.UpdateAsync(wmsReceiptOrder,ignoreNullValues:true);
        }

        /// <summary>
        /// 获取收货单
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet("detail")]
        public async Task<WmsReceiptOrderOutput> Get([FromQuery] QueryeWmsReceiptOrderInput input)
        {
            return (await _wmsReceiptOrderRep.DetachedEntities.FirstOrDefaultAsync(u => u.Id == input.Id)).Adapt<WmsReceiptOrderOutput>();
        }

        /// <summary>
        /// 获取收货单列表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet("list")]
        public async Task<List<WmsReceiptOrderOutput>> List([FromQuery] WmsReceiptOrderInput input)
        {
            return await _wmsReceiptOrderRep.DetachedEntities.ProjectToType<WmsReceiptOrderOutput>().ToListAsync();
        }    
         /// <summary>
        /// Excel模板导入收货单功能
        /// </summary>
        /// <param name="file">Excel模板文件</param>
        /// <param name="importExcelType">Excel导入方式</param>
        /// <returns>导入的记录数</returns>
        [HttpPost("fromExcel")]
        public async Task<int> FromExcelAsync(IFormFile file, [FromQuery] ImportExcelType importExcelType)
        {
            int size = 200;
            var excelTemplate = await _sysExcelTemplateService.GetByAppNameAndClassNameAndVersionAsync("WmsReceiptOrder", "v2");
            if (excelTemplate == null) throw Oops.Oh(ErrorCode.Excel002);
            var keys = excelTemplate.UnionUniqueFields.Split(",") ?? Array.Empty<string>();
            for (var i = 0; i < keys.Length; i++) 
            {
                keys[i] = keys[i]?.Trim() ?? string.Empty;
            }
            ExcelUtil.FromExcel(file, excelTemplate.HeadStartLine, excelTemplate.DataStartLine, out List<string> headers, out List<List<object?>> data, out string sheetName);
            List<WmsReceiptOrderOutput> wmsReceiptOrderList = DataConvertUtil.ToObjectList(headers, data, sheetName, keys, excelTemplate?.DataStartLine ?? 2, out Dictionary<string, WmsReceiptOrderOutput> dict);
            List<Dictionary<string, object>> uniqueKeyValueDictList = wmsReceiptOrderList.ParseUniqueKeyValueDictList(keys.ToList(), excelTemplate?.DataStartLine ?? 2, sheetName);
            var filters = DataConvertUtil.GetExpressionListByUniqueDict<WmsReceiptOrder>(keys.ToList(), uniqueKeyValueDictList, size);
            var selectKeys = keys.ToList();
            if(!selectKeys.Contains("Id")) selectKeys.Add("Id");
            var selector = DataConvertUtil.GetSelectExpressionListByUniqueDict<WmsReceiptOrder, WmsReceiptOrderOutput>(selectKeys);
            List<WmsReceiptOrder> updates = new();
            List<WmsReceiptOrder> adds = new();

            lock (_lock)
            {
                foreach (var filter in filters)
                {
                    var wmsReceiptOrderExistSubList = _wmsReceiptOrderRep.Where(filter).Select(selector).ToList();
                    wmsReceiptOrderExistSubList.ForEach(x => 
                    {
                        var k = DataConvertUtil.GetKey(x, keys);
                        if (dict.ContainsKey(k)) dict[k].Id = x.Id;
                    });
                }
                foreach (var wmsReceiptOrder in wmsReceiptOrderList) 
                {
                    if (wmsReceiptOrder.Id > 0)
                    {
                        if (importExcelType == ImportExcelType.ADD_AND_UPDATE) updates.Add(wmsReceiptOrder.Adapt<WmsReceiptOrder>());
                    }
                    else 
                    {
                        adds.Add(wmsReceiptOrder.Adapt<WmsReceiptOrder>());
                    }
                }

                if (importExcelType == ImportExcelType.ADD_AND_UPDATE) updates.ForEach(x => _wmsReceiptOrderRep.Update(x));
                

                var maxId = _wmsReceiptOrderRep.DetachedEntities.OrderByDescending(x => x.Id).Select(x => x.Id).FirstOrDefault();
                adds.ForEach(x => x.Id = ++maxId);    
                Db.GetDbContext().Set<WmsReceiptOrder>().AddRange(adds);  
                Db.GetDbContext().SaveChanges();
               
            }
            await Task.CompletedTask;
            return adds.Count;
        }

        /// <summary>
        /// 根据版本下载收货单的Excel导入模板
        /// </summary>
        /// <param name="version">模板版本</param>
        /// <returns>下载的模板文件</returns>
        [HttpGet("downloadExcelTemplate")]
        public async Task<IActionResult> DownloadExcelTemplate([FromQuery] string version)
        {
            var excelTemplate = await _sysExcelTemplateService.GetByAppNameAndClassNameAndVersionAsync("WmsReceiptOrder", version);
            if (excelTemplate == null) throw Oops.Oh(ErrorCode.Excel002);
            var path = Path.Combine(@"\", excelTemplate.TemplateFileName);
            Stream ms = FileUtil.Download(path, excelTemplate.TemplateFileName);
            var fileName = HttpUtility.UrlEncode($"{excelTemplate.Name}导入模板.xlsx", Encoding.GetEncoding("UTF-8"));
            return new FileStreamResult(ms, "application/octet-stream") { FileDownloadName = fileName };
        }
        /// <summary>
        /// 根据收货单查询参数导出Excel
        /// </summary>
        /// <param name="input">收货单查询参数</param>
        /// <returns>导出的Excel文件</returns>
        [HttpGet("toExcel")]
        public async Task<IActionResult> ToExcelAsync([FromQuery] WmsReceiptOrderSearchNonPage input)
        {
            var wmsReceiptOrderList = await ListNonPageAsync(input);
            MemoryStream ms = new();
            DataConvertUtil.ToExcelData(wmsReceiptOrderList, _sysDictTypeRep, _sysDictDataRep, out List<string> headers, 
                out List<List<object>> data, out string sheetName);
            var excelTemplate = await _sysExcelTemplateService.GetByAppNameAndClassNameAndVersionAsync("WmsReceiptOrder", "v1");
            if (excelTemplate != null)
            {
                ExcelUtil.ToExcel(excelTemplate.TemplateFileName, headers, data, sheetName, excelTemplate.HeadStartLine, excelTemplate.DataStartLine, ms);
            }
            else 
            {
                ExcelUtil.ToExcel(headers, data, sheetName, ms);
            }
            ms.Position = 0;
            var fileName = HttpUtility.UrlEncode($"{sheetName}[{DateTimeOffset.Now:yyyy-MM-dd}].xlsx", Encoding.GetEncoding("UTF-8"));
            return new FileStreamResult(ms, "application/octet-stream") { FileDownloadName = fileName };
        }
    }
}
